package com.zhituanbox.extensions.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.support.AbstractResourceBasedMessageSource;
import org.springframework.util.CollectionUtils;

import java.text.MessageFormat;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 扩展消息
 *
 * @author LiuYang
 * @since 2020/9/21
 * @version 1.0.0
 */
public class ExtensionsMessageSource extends AbstractResourceBasedMessageSource {
    private final Logger log = LoggerFactory.getLogger(ExtensionsMessageSource.class);
    @Lazy
    @Autowired
    private ObjectProvider<List<ExtensionsMessageSourceResolveCodeProvider>> extensionsMessageProviders;
    /**
     * 接口名，用于日志打印
     */
    private final String extensionsMessageProviderSimpleClassName = ExtensionsMessageSourceResolveCodeProvider.class.getSimpleName();

    /** {@inheritDoc} */
    @Override
    protected MessageFormat resolveCode(String code, Locale locale) {
        List<ExtensionsMessageSourceResolveCodeProvider> messageProviders = extensionsMessageProviders.getIfAvailable();
        if (CollectionUtils.isEmpty(messageProviders)) {
            log.warn("{} is empty", extensionsMessageProviderSimpleClassName);
            return null;
        }
        if (log.isDebugEnabled()) {
            String simpleClassNameStr = messageProviders.stream().map(AopUtils::getTargetClass).map(Class::getSimpleName).collect(Collectors.joining(","));
            log.debug("{}: find impl [{}]", extensionsMessageProviderSimpleClassName, simpleClassNameStr);
        }
        String message = null;
        for (ExtensionsMessageSourceResolveCodeProvider messageProvider : messageProviders) {
            final String simpleName = AopUtils.getTargetClass(messageProvider).getSimpleName();
            Optional<String> resolveCode = messageProvider.resolveCode(code, locale);
            if (resolveCode.isPresent()) {
                message = resolveCode.get();
                log.debug("{}.resolveCode({},{}) result is [{}]", simpleName, code, locale, message);
                break;
            } else {
                log.debug("{}.resolveCode({},{}) result is empty", simpleName, code, locale);
            }
        }
        return Objects.isNull(message) ? null : createMessageFormat(message, locale);
    }
}
